package com.example.research.controller;

import com.example.research.model.Department;
import com.example.research.service.DepartmentService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/departments")
public class DepartmentController {

    private final DepartmentService departmentService;

    public DepartmentController(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    @GetMapping
    public String listDepartments(Model model) {
        model.addAttribute("departments", departmentService.findAll());
        return "departments/list";
    }

    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("department", new Department());
        return "departments/add";
    }

    @PostMapping("/add")
    public String addDepartment(@ModelAttribute Department department,
                                RedirectAttributes redirectAttributes) {
        departmentService.save(department);
        redirectAttributes.addFlashAttribute("successMessage", "部门添加成功");
        return "redirect:/departments";
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable("id") Integer id, Model model) {
        Department department = departmentService.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("无效的部门ID: " + id));
        model.addAttribute("department", department);
        return "departments/edit";
    }

    @PostMapping("/edit/{id}")
    public String updateDepartment(@PathVariable("id") Integer id,
                                   @ModelAttribute Department department,
                                   RedirectAttributes redirectAttributes) {
        if (!departmentService.existsById(id)) {
            throw new IllegalArgumentException("无效的部门ID: " + id);
        }
        department.setDeptId(id);
        departmentService.save(department);
        redirectAttributes.addFlashAttribute("successMessage", "部门更新成功");
        return "redirect:/departments";
    }

    @GetMapping("/delete/{id}")
    public String deleteDepartment(@PathVariable("id") Integer id,
                                   RedirectAttributes redirectAttributes) {
        departmentService.delete(id);
        redirectAttributes.addFlashAttribute("successMessage", "部门删除成功");
        return "redirect:/departments";
    }
}
